<template>
  <div>
    <el-container>
      <el-aside width="230px">
        <div class="app_card mb-2 pt-4  pb-4" style="height:calc(100vh - 180px);overflow-y: scroll;padding:0">
          <el-menu :default-active="queryParam.buildingId" @select="handleSelect">
            <template v-for="(item, idx) of bildingList">
              <el-menu-item :index="item.id.toString()" :class="queryParam.buildingId==item.id?'is-active':''">
                {{ item.name }}
              </el-menu-item>
            </template>
          </el-menu>
        </div>
      </el-aside>
      <el-main>
        <!-- {{dataOfTable.length}}
        {{riskRefList}} -->
        <div class="app_card mb-2 pt-4 pb-4">
          <div class="d-flex justify-content-between align-items-center">
            <div class="flex-grow-1 d-flex">
              <el-radio-group class="radio_button mr-5" v-model="queryForm.radio_floor" @change="floorChange">
                <el-radio-button label="-1">全部</el-radio-button>
                <el-radio-button label="-2">上课中</el-radio-button>
                <el-radio-button label="-3">故障教室</el-radio-button>
              </el-radio-group>
              <el-checkbox v-model="automaticPolling" label="自动轮询" @change="changeAutomaticPolling" />
              <el-tooltip effect="customized">
                <template #content>
                  <div>开启自动轮询10秒刷新一次</div>
                </template>
                <el-button link><el-icon>
                    <Warning />
                  </el-icon></el-button>
              </el-tooltip>
            </div>
            <div class="d-flex">
              <el-radio-group v-model="radioIcon" @change="switchIcon">
                <el-radio label="4">4画面</el-radio>
                <el-radio label="6">6画面</el-radio>
              </el-radio-group>
            </div>
          </div>
        </div>

        <!-- 还不清数用户视屏是什么方式显示后期可参考此方法
  https://juejin.cn/post/7250284063210373178?searchId=20231028232942FA246904271D45C2A053 -->
        <div class="app_card pt-4  pb-5">
          <div style="height:calc(100vh - 300px);overflow-y: scroll;">
            <!-- <div class="t-c" v-if="dataOfTable.length==0&&!loading" style="padding-top:calc(50vh - 200px);">
              <el-icon size="80" color="#191e4b">
                <VideoCameraFilled />
              </el-icon>
              <div class="text-white-50 text-16">暂无数据</div>
            </div> -->

            <div class="w100 t-c monitor-none" style="height:calc(100vh - 300px);padding-top:calc(50vh - 160px);    box-sizing: border-box;" v-if="dataOfTable.length==0&&!loading">
              <img src="@/assets/img/monitor.png" width="100" />
              <div class="text-white-50 text-16">暂无数据</div>

            </div>

            <el-row :gutter="15" class="w100">
              <el-col class="mb-3 p_relative" :xs="12" :sm="12" :lg="radioIcon == '4' ? { span: col12 } : { span: col8 }" v-for="(item, index) in dataOfTable" :key="index">
                <div class="class_name" :style="`bottom: ${!item.playUrlList.length?'0':'4px'}px; `">{{item.name}}</div>
                <div class="mb-3" style="height: 35px;box-sizing: border-box;">
                  <el-radio-group class="radio_button" v-model="item.flvUrl" @change="switchVideo(item,item.flvUrl,index)">
                    <template v-for="play in item.playUrlList">
                      <el-radio-button v-if="play.flvUrl" :label="play.index">{{play.title}}</el-radio-button>
                    </template>
                  </el-radio-group>
                </div>
                <div class="w100 t-c monitor-none" v-if="!item.playUrlList.length">
                  <img src="@/assets/img/monitor.png" width="100" />
                </div>
                <FlvPlayer v-show="item.playUrlList.length" :ref="getRiskRef" :id="`video${index}`" height="300"></FlvPlayer>
              </el-col>
            </el-row>
          </div>
          <div class="mt-3">
            <el-pagination :hide-on-single-page="true" v-model:page-size="queryParam.limit" :page-sizes="paginationOption.pageSizes" background v-model:currentPage="queryParam.page" :layout="paginationOption.layout" :total="paginationOption.totalCount" @size-change="handleChangeSize" @current-change="handleChangeCurrent" />
            <!-- <el-pagination v-model:page-size="queryParam.limit" :page-sizes="paginationOption.pageSizes" background v-model:currentPage="queryParam.page" :background="false" :layout="paginationOption.layout" :total="paginationOption.totalCount" @size-change="handleChangeSize" @current-change="handleChangeCurrent" /> -->
          </div>
        </div>

        <div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
/**
 * 教学监控
 */
import { ref, onMounted, nextTick, onUnmounted } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import FlvPlayer from '@/components/flvPlayer/index.vue'
import Pagination from '@/components/pagination/index.vue';

// ======================================================
//                     轮播start
// ======================================================
const automaticPolling = ref(false);
// 创建定时器
let intervalId;
// 在组件挂载时启动定时器
const changeAutomaticPolling = (val) => {
  //自动轮播
  if (val) {
    intervalId = setInterval(() => {
      // 第一页
      if (pageNum.value > 1) {
        if (queryParam.value.page == pageNum.value) {
          onReset()
        } else {
          //下一页
          queryParam.value.page++;
          loadData()
        }
      }
    }, 10000); // 1000毫秒，即1秒
  } else {//取消轮播
    clearInterval(intervalId);
  }
}


const onReset = () => {
  queryParam.value.page = 1;
  pageNum.value = 0
  paginationOption.value.totalCount = 0
  loadData()
}


// 在组件卸载时清除定时器，防止内存泄漏
onUnmounted(() => {
  clearInterval(intervalId);
});
// ======================================================
//                     轮播end
// ======================================================

// ======================================================
//                      变量声明
// ======================================================
//教室视频数据
// const playUrlDto = ref({})
//视频播放控件
let riskRefList = ref([]);
const getRiskRef = (el) => {
  // console.error('el====', el)
  if (el) {
    riskRefList.value.push(el);
  }
};
const switchVideo = (item, flvUrl, index) => {
  let _index = parseInt(flvUrl)
  let _flvUrl = item.playUrlList[_index].flvUrl
  // console.log('_flvUrl==', _flvUrl)
  // console.log('ref==', riskRefList.value[index])
  riskRefList.value[index].load(_flvUrl)
}
// 表格数据
const dataOfTable = ref([]);
// 表格查询参数
const queryForm = ref({
  buildingId: "",
  radio_floor: "-1",
})
const loading = ref(false);
//总页数
const pageNum = ref(0);
// 表格查询参数
const queryParam = ref({
  sort: "id",
  order: "desc",
  query: "",
  limit: 4,
  page: 1,
})


// 分页栏配置数据
const paginationOption = ref({
  layout: 'total, sizes, prev, pager, next, jumper',
  pageSizes: [4, 6],
  totalCount: 0,

})

// 教室分组数据
const dataOfGroups = ref([]);
const defaultProps = {
  children: 'children',
  label: 'label',
}
//4画面 6画面
const radioIcon = ref('4');
const col12 = ref(12);
const col8 = ref(8);

const bildingDto = ref(null)
const bildingList = ref([]);
function getBuildList(tree = false) {
  const loadingInstance = ElLoading.service({ text: '加载中...' })
  EsAjax.post(ApiUrls.buildingAll, {}).then(res => {
    if (res.data.data && res.data.data.length) {
      bildingList.value = res.data.data || [];
      queryParam.value.buildingId = `${bildingList.value[0].id}`
      bildingDto.value = bildingList.value[0]
      loadData();
    }
  }).catch(err => {
    ElMessage.error(err.message);
  }).finally(() => {
    loadingInstance.close()
  })
}

// 点击一级目录
const handleSelect = (key) => {
  queryParam.value.buildingId = key.toString();
  let obj = bildingList.value.find(item => item.id == key)
  if (obj) {
    bildingDto.value = obj
  }
  showRoom.value = false
  loadData();
};
// ======================================================
//                      点击操作
// ======================================================
const floorChange = () => {
  clearInterval(intervalId);
  pageNum.value = 0
  paginationOption.value.totalCount = 0
  loadData()
  changeAutomaticPolling(automaticPolling.value)
}
const switchIcon = (val) => {
  handleChangeSize(parseInt(val));
}
// ======================================================
//                      处理事件
// ======================================================
// 处理分页尺寸
const handleChangeSize = (val) => {
  queryParam.value.page = 1;
  queryParam.value.limit = val;
  loadData()
}

// 处理页码
const handleChangeCurrent = (val) => {
  queryParam.value.page = val;
  loadData()
}

const loadData = async () => {

  riskRefList.value = []
  // playUrlDto.value = []
  dataOfTable.value = []

  let _queryParam = queryParam.value
  _queryParam.query = ''

  if (queryForm.value.buildingId) {
    _queryParam.query = "buildingId=" + queryForm.value.buildingId;
  }
  _queryParam.offset = (_queryParam.page - 1) * _queryParam.limit || 0;
  loading.value = true
  let url = ApiUrls.roomSearch

  if (queryForm.value.radio_floor == '-2') {//上课中
    url = ApiUrls.roomInclass
  } else if (queryForm.value.radio_floor == '-3') {//故障
    url = ApiUrls.roomFault
  }
  const loadingInstance = ElLoading.service({ text: '加载中...' })
  EsAjax.post(url, _queryParam).then(async (res) => {
    if (res.data.code != 200) {
      ElMessage.warning(res.data.data + res.data.msg);
      return;
    }
    let { list, totalCount } = res.data.data
    if (list && list.length) {
      //   list.forEach(async (element) => {
      //     element.flvUrl = ""
      //     playUrlDto.value[element.id] = []
      //   });
      const data = await Promise.all(
        list.map(async (item) => {
          item.flvUrl = ""
          // playUrlDto.value[item.id] = []
          item.playUrlList = []
          //请求视屏流
          let playUrlList = await getPlaywindows(item.id);
          // console.log('playUrlList===', playUrlList)
          if (playUrlList) {
            playUrlList.forEach((play, index) => {
              play.index = index
              // if (index == 0) {
              //   play.flvUrl = 'https://sf1-hscdn-tos.pstatp.com/obj/media-fe/xgplayer_doc_video/flv/xgplayer-demo-360p.flv'
              // }
              // console.log('item.flvUrl===', item.flvUrl)
              if (play.flvUrl && `${item.flvUrl}` == "") {
                item.flvUrl = index
              }

            });
            item.playUrlList = playUrlList

            // riskRefList.value[index].load(windowsDto?.playUrlList[0].flvUrl)
          }
          return item.playUrlList.length
          // let playUrlList = await getPlaywindows(item.id);
          // return getPlaywindows(item.id);
        }),
      );
      // console.error('data===', data)

      if (data.length == list.length) {
        dataOfTable.value = list;
        setTimeout(() => {

          nextTick(() => {
            dataOfTable.value.forEach((element, index) => {
              // console.log('element.flvUrl===', element.flvUrl)
              // 
              if (`${element.flvUrl}`) {
                // element.flvUrl = element?.playUrlList[0].index
                riskRefList.value[index].load(element?.playUrlList[element.flvUrl].flvUrl)
              }
            });
          })
        }, 1000);


      }
    }





    // //获取教室视频
    // nextTick(() => {
    //   riskRefList.value = []
    //   if (dataOfTable.value && dataOfTable.value.length) {
    //     dataOfTable.value.forEach(async (element) => {
    //       await getPlaywindows(element.id)
    //     });
    //   }
    // })
    //页数
    pageNum.value = Math.ceil(totalCount / _queryParam.limit);
    //总数量
    paginationOption.value.totalCount = totalCount
  }).catch(err => {
    ElMessage.error(err.message);
  }).finally(() => {
    loading.value = false
    loadingInstance.close()
  })
}


/**获取视屏流 */
const getPlaywindows = (id) => {
  // console.log('id==', id)

  return new Promise((resolve, reject) => {

    EsAjax.post(ApiUrls.roomPlaywindows, { id: id }).then(res => {
      // console.log(res)
      if (res.data.code != 200) {
        ElMessage.warning(res.data.data + res.data.msg);
        return;
      }
      let { data } = res.data
      let { windows = [] } = data
      // console.log('windows==', windows)
      // playUrlDto.value[id] = []
      if (windows && windows.length) {
        let windowsDto = windows[0];
        // if (id == '111') {
        //   resolve([])
        // } else {
        // }
        resolve(windowsDto?.playUrlList || [])

      } else {
        resolve([])
      }
    }).catch(err => {
      // ElMessage.error(err.message);
      resolve([])
    }).finally(() => {
    })

  })


}




onMounted(() => {
  getBuildList()
})

</script>
<style lang="less" scoped>
.class_name {
  position: absolute;
  left: 7.5px;
  right: 7.5px;
  bottom: 4px;
  height: 1.4em;
  font-size: 18px;
  font-weight: 500;
  padding: 20px 50px 12px 13px;
  margin: 0;
  border-radius: 0 0 10px 10px;
  background-image: -webkit-linear-gradient(
    top,
    rgba(0, 0, 0, 0) 0,
    rgba(0, 0, 0, 0.7) 100%
  );
  background-image: linear-gradient(
    to bottom,
    rgba(0, 0, 0, 0) 0,
    rgba(0, 0, 0, 0.7) 100%
  );
  color: #fff;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.5);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-wrap: normal;
  z-index: 1;
}
.monitor-none {
  height: 300px;
  background: #191e4b;
  padding-top: 100px;
  box-sizing: border-box;
  border-radius: 10px;
}
::v-deep(.el-pagination__sizes) {
  display: none;
}
::v-deep(.el-pagination__jump) {
  display: none;
}
</style>
  
